package com.darkness.rpc.framework.protocol.dark;

import com.darkness.rpc.framework.common.Invocation;
import com.darkness.rpc.framework.common.util.ProtostuffUtil;
import com.darkness.rpc.framework.protocol.RequestHandler;
import org.apache.dubbo.common.io.Bytes;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author darkness
 * @time 2022/4/15 13:46
 * @description
 */
public class DarkRequestHandler implements RequestHandler {
    @Override
    public Object handleRequest(String ip, Integer port, Invocation request, Class<?> returnType) {
        try {
            Socket socket = new Socket(ip, port);
            OutputStream outputStream = socket.getOutputStream();
            byte[] requestBytes = ProtostuffUtil.serializer(request);
            int length = requestBytes.length;
            byte[] bytes = new byte[4];
            // int是4个字节,存放入 byte数组
            for (int i = 3; i >= 0; i--) {
                bytes[i] = (byte) length;
                // 对原数据进行右移8位,获得第二个字节
                length = length >> 8;
            }
            outputStream.write(bytes);
            outputStream.write(requestBytes);
            InputStream inputStream = socket.getInputStream();
            byte[] readInt = new byte[4];
            byte[] resultBytes = new byte[8192];
            // 将4个字节的length读出来忽略
            inputStream.read(readInt);
            int read = inputStream.read(resultBytes);
            byte[] res = Bytes.copyOf(resultBytes, read);
            return ProtostuffUtil.deserializer(res, returnType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
